<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>字符串的Iterator接口</title>
</head>
<body>
    <h1>字符串的Iterator接口</h1>

    <script>
        // 字符串的Iterator接口
        const str = "hello";
        const iterator = str[Symbol.iterator]();

        console.log(iterator.next()); // { value: "h", done: false }
        console.log(iterator.next()); // { value: "e", done: false }
        console.log(iterator.next()); // { value: "l", done: false }
        console.log(iterator.next()); // { value: "l", done: false }
        console.log(iterator.next()); // { value: "o", done: false }
        console.log(iterator.next()); // { value: undefined, done: true }

        // for...of循环
        for (let char of "hello") {
            console.log(char);
        }

        // 处理Unicode字符
        let text = '𠮷a';
        for (let char of text) {
            console.log(char); // 正确输出𠮷和a
        }

        // 字符串的其他遍历方法对比
        // 传统for循环
        for (let i = 0; i < text.length; i++) {
            console.log(text[i]); // 无法正确处理𠮷字
        }

        // for...of循环
        for (let char of text) {
            console.log(char.codePointAt(0).toString(16)); // 输出码点
        }
    </script>
</body>
</html> 